package com.adamjwh.pratice.offer;


import com.adamjwh.tools.TreeNode;

/**
 * 输入某二叉树的前序遍历和中序遍历的结果，请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}，则重建二叉树并返回。
 */

public class ReConstructTree {
    public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
        TreeNode root = new TreeNode(pre[0]);       //根节点
        int len = pre.length;

        if(len == 1) {      //只有一个数
            root.left = null;
            root.right = null;
            return root;
        }

        int rootval = root.val;
        int index = 0;      //存储中序遍历根节点下标
        for(int i=0; i<len; i++) {
            if(rootval == in[i]) {
                index = i;
                break;
            }
        }

        //创建左子树
        if(index > 0) {
            int[] pre_left = new int[index];
            int[] in_left = new int[index];

            for(int i=0; i<index; i++) {
                pre_left[i] = pre[i+1];
                in_left[i] = in[i];
            }

            root.left = reConstructBinaryTree(pre_left, in_left);
        } else {
            root.left = null;
        }

        //创建右子树
        if(len-index-1 > 0) {
            int[] pre_right = new int[len-index-1];
            int[] in_right = new int[len-index-1];

            for(int i=index+1; i<len; i++) {
                pre_right[i-index-1] = pre[i];
                in_right[i-index-1] = in[i];
            }

            root.right = reConstructBinaryTree(pre_right, in_right);
        } else {
            root.right = null;
        }

        return root;
    }

    public static void main(String[] args) {
        int[] pre = {1,2,3,4,5,6,7};
        int[] in = {3,2,4,1,6,5,7};
        new ReConstructTree().reConstructBinaryTree(pre, in);
    }
}
